import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import PoseCanvas from './PoseCanvas';
import TomatoProgress from './TomatoProgress';
import TomatoTree from './TomatoTree';
import { Button } from './ui/button';
import { IntensityAnalyzer, INITIAL_INTENSITY_METRICS } from '@/lib/mediapipe/intensity';
import { AIIntensityEvaluator, type AIIntensityFeedback } from '@/lib/ai/intensityEvaluator';

const ENCOURAGEMENT_MESSAGES = [
  '加油呀，再运动一下就能开始干活啦！💪',
  '保持节奏，番茄马上就要熟啦 🍅',
  '动作幅度再大一点，效果更好哦 ✨',
  '太棒了，再坚持一会儿就能满番茄！',
  '别偷懒，动起来！以后腰不酸 😂',
];

interface ExerciseModalProps {
  isVisible: boolean;
  onComplete: () => void;
  onSkip: () => void;
  targetReps?: number;
}

interface ExerciseAction {
  id: string;
  name: string;
  emoji: string;
  instructions: string;
  targetReps: number;
  detector: (poseLandmarks: any[]) => boolean;
}

const detectRaiseArmsAction = (poseLandmarks: any[]) => {
  if (!poseLandmarks || poseLandmarks.length < 33) return false;
  const leftWrist = poseLandmarks[15];
  const rightWrist = poseLandmarks[16];
  const nose = poseLandmarks[0];
  const leftShoulder = poseLandmarks[11];
  const rightShoulder = poseLandmarks[12];
  const leftArmRaised = leftWrist.y < nose.y && leftWrist.y < leftShoulder.y;
  const rightArmRaised = rightWrist.y < nose.y && rightWrist.y < rightShoulder.y;
  const armsSpread = Math.abs(leftWrist.x - rightWrist.x) > 0.3;
  return leftArmRaised && rightArmRaised && armsSpread;
};

const detectSideStretchAction = (poseLandmarks: any[]) => {
  if (!poseLandmarks || poseLandmarks.length < 33) return false;
  const leftWrist = poseLandmarks[15];
  const rightWrist = poseLandmarks[16];
  const leftShoulder = poseLandmarks[11];
  const rightShoulder = poseLandmarks[12];
  const leftHip = poseLandmarks[23];
  const rightHip = poseLandmarks[24];
  const armsRaised = leftWrist.y < leftShoulder.y && rightWrist.y < rightShoulder.y;
  if (!armsRaised) return false;
  const shoulderCenter = (leftShoulder.x + rightShoulder.x) / 2;
  const hipCenter = (leftHip.x + rightHip.x) / 2;
  const torsoTilt = Math.abs(shoulderCenter - hipCenter);
  return torsoTilt > 0.08;
};

const ExerciseModal: React.FC<ExerciseModalProps> = ({
  isVisible,
  onComplete,
  onSkip,
  targetReps: defaultTarget = 5
}) => {
  const intensityAnalyzerRef = useRef(new IntensityAnalyzer());
  const [aiEvaluator, setAiEvaluator] = useState<AIIntensityEvaluator | null>(null);
  const [intensityMetrics, setIntensityMetrics] = useState(INITIAL_INTENSITY_METRICS);
  const [aiFeedback, setAiFeedback] = useState<AIIntensityFeedback | null>(null);
  const [isRequestingFeedback, setIsRequestingFeedback] = useState(false);
  const [mode, setMode] = useState<'guided' | 'free'>('guided');
  const [hasFreeCompletion, setHasFreeCompletion] = useState(false);
  const lastFeedbackTimestampRef = useRef(0);
  const [feedbackQueue, setFeedbackQueue] = useState<{ text: string; suggestions?: string[] }[]>([]);
  const [showFeedbackBubble, setShowFeedbackBubble] = useState(false);
  const feedbackStageIndexRef = useRef(0);
  const feedbackTimeoutRef = useRef<number | null>(null);
  const encouragementIntervalRef = useRef<number | null>(null);

  useEffect(() => {
    return () => {
      if (feedbackTimeoutRef.current) {
        window.clearTimeout(feedbackTimeoutRef.current);
      }
      if (encouragementIntervalRef.current) {
        window.clearInterval(encouragementIntervalRef.current);
      }
    };
  }, []);

  useEffect(() => {
    const aiKey = import.meta.env.VITE_BAIDU_API_KEY as string | undefined;
    if (aiKey && !aiEvaluator) {
      setAiEvaluator(new AIIntensityEvaluator({ apiKey: aiKey }));
    }
  }, [aiEvaluator]);

  const actions = useMemo<ExerciseAction[]>(
    () => [
      {
        id: 'raise_arms',
        name: '伸展唤醒',
        emoji: '🙆‍♀️',
        instructions: '双手举过头顶，与身体拉出大幅度弧线，保持 1 秒',
        targetReps: 5,
        detector: detectRaiseArmsAction
      },
      {
        id: 'side_stretch',
        name: '侧身伸展',
        emoji: '🤸‍♀️',
        instructions: '双臂上举后向左右侧缓慢伸展，保持身体稳定',
        targetReps: 6,
        detector: detectSideStretchAction
      }
    ],
    []
  );

  const lastActionIdRef = useRef<string | null>(null);
  const [currentAction, setCurrentAction] = useState<ExerciseAction>(actions[0]);
  const [currentReps, setCurrentReps] = useState(0);
  const [isDetecting, setIsDetecting] = useState(false);
  const [lastActionTime, setLastActionTime] = useState(0);

  useEffect(() => {
    if (!isVisible) return;
    intensityAnalyzerRef.current.reset();
    setIntensityMetrics(INITIAL_INTENSITY_METRICS);
    setAiFeedback(null);
    setFeedbackQueue([]);
    feedbackStageIndexRef.current = 0;
    if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
    if (encouragementIntervalRef.current) window.clearInterval(encouragementIntervalRef.current);
    setShowFeedbackBubble(false);
    setHasFreeCompletion(false);
    lastFeedbackTimestampRef.current = 0;

    if (mode === 'free') {
      encouragementIntervalRef.current = window.setInterval(() => {
        setFeedbackQueue((prev) => {
          const message = ENCOURAGEMENT_MESSAGES[Math.floor(Math.random() * ENCOURAGEMENT_MESSAGES.length)];
          return [...prev, { text: message }];
        });
        setShowFeedbackBubble(true);
        if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
        feedbackTimeoutRef.current = window.setTimeout(() => setShowFeedbackBubble(false), 2200);
      }, 15000);
    }
  }, [isVisible, mode]);

  useEffect(() => {
    if (!isVisible || mode !== 'guided') return;
    const available = actions.filter((action) => action.id !== lastActionIdRef.current);
    const nextAction = available[Math.floor(Math.random() * available.length)] ?? actions[0];
    setCurrentAction(nextAction);
    lastActionIdRef.current = nextAction.id;
    setCurrentReps(0);
    setIsDetecting(false);
    setLastActionTime(0);
  }, [isVisible, mode, actions]);

  const effectiveTargetReps = currentAction?.targetReps ?? defaultTarget;

  const handlePoseDetected = useCallback(
    (poseLandmarks: any[]) => {
      const now = Date.now();

      if (mode === 'free') {
        const metrics = intensityAnalyzerRef.current.analyze(poseLandmarks, now);
        setIntensityMetrics(metrics);

        const fallbackStages = [25, 60, 100];
        const fallbackMessages = [
          '状态不错，保持这个节奏！',
          '很好！幅度再大一点会更有效！',
          '马上就成功啦，再坚持一下！',
        ];
        if (
          feedbackStageIndexRef.current < fallbackStages.length &&
          metrics.movementPoints >= fallbackStages[feedbackStageIndexRef.current]
        ) {
          const stageMessage = fallbackMessages[feedbackStageIndexRef.current] ?? fallbackMessages.slice(-1)[0];
          feedbackStageIndexRef.current += 1;
          setFeedbackQueue((prev) => [...prev, { text: stageMessage }]);
          setShowFeedbackBubble(true);
          if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
          feedbackTimeoutRef.current = window.setTimeout(() => setShowFeedbackBubble(false), 2400);
        }

        // 当所有番茄都充满时完成
        if (!hasFreeCompletion && metrics.completedTomatoes >= 5) {
          setHasFreeCompletion(true);
          setFeedbackQueue((prev) => [...prev, { text: '所有番茄都成熟啦！休息得很充足！🎉' }]);
          setShowFeedbackBubble(true);
          if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
          feedbackTimeoutRef.current = window.setTimeout(() => setShowFeedbackBubble(false), 2600);
          setTimeout(() => {
            onComplete();
          }, 1500);
        }

        if (
          aiEvaluator &&
          !isRequestingFeedback &&
          now - lastFeedbackTimestampRef.current > 4000 &&
          metrics.overallScore > 0.25
        ) {
          lastFeedbackTimestampRef.current = now;
          setIsRequestingFeedback(true);
          aiEvaluator
            .generateFeedback(metrics)
            .then((feedback) => {
              setAiFeedback(feedback);
              setFeedbackQueue((prev) => [...prev, { text: feedback.feedback, suggestions: feedback.suggestions.slice(0, 2) }]);
              setShowFeedbackBubble(true);
              if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
              feedbackTimeoutRef.current = window.setTimeout(() => setShowFeedbackBubble(false), 2400);
            })
            .finally(() => setIsRequestingFeedback(false));
        }
        return;
      }

      if (now - lastActionTime < 1000) return;
      if (!currentAction?.detector) return;

      if (currentAction.detector(poseLandmarks) && !isDetecting) {
        setIsDetecting(true);
        setTimeout(() => {
          if (currentAction.detector(poseLandmarks)) {
            setCurrentReps((prev) => {
              const newReps = prev + 1;
              if (newReps >= effectiveTargetReps) {
                if ((window as any).confetti) {
                  (window as any).confetti({
                    particleCount: 100,
                    spread: 70,
                    origin: { y: 0.6 },
                    colors: ['#FF8A80', '#A8D8B9', '#FFB74D']
                  });
                }
                setTimeout(() => {
                  onComplete();
                }, 2000);
              }
              return newReps;
            });
            setLastActionTime(Date.now());
          }
          setIsDetecting(false);
        }, 500);
      }
    },
    [
      mode,
      aiEvaluator,
      hasFreeCompletion,
      isRequestingFeedback,
      currentAction,
      effectiveTargetReps,
      lastActionTime,
      isDetecting,
      onComplete
    ]
  );

  const progress = mode === 'guided'
    ? Math.min((currentReps / effectiveTargetReps) * 100, 100)
    : Math.min(intensityMetrics.completionRatio * 100, 100);

  const { overallScore, amplitude, durationRatio, frequencyRatio, repCount, elapsedSeconds, isActive, movementPoints } =
    intensityMetrics;

  if (!isVisible) return null;

  return (
    <div className={`modal-overlay ${isVisible ? 'visible' : ''}`}>
      <div className="modal-content">
        <div className="flex flex-col gap-6">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div>
              <p className="text-sm text-muted-foreground">选择休息模式</p>
              <div className="mt-2 inline-flex items-center rounded-full border border-border/40 bg-background p-1 text-sm">
                <button
                  className={`px-4 py-1 rounded-full transition-colors ${
                    mode === 'guided' ? 'bg-primary text-white' : 'text-muted-foreground'
                  }`}
                  onClick={() => setMode('guided')}
                >
                  AI 指定运动
                </button>
                <button
                  className={`px-4 py-1 rounded-full transition-colors ${
                    mode === 'free' ? 'bg-primary text-white' : 'text-muted-foreground'
                  }`}
                  onClick={() => {
                    setMode('free');
                    intensityAnalyzerRef.current.reset();
                    setIntensityMetrics(INITIAL_INTENSITY_METRICS);
                    setAiFeedback(null);
                    setFeedbackQueue([]);
                    feedbackStageIndexRef.current = 0;
                    if (feedbackTimeoutRef.current) window.clearTimeout(feedbackTimeoutRef.current);
                    if (encouragementIntervalRef.current) window.clearInterval(encouragementIntervalRef.current);
                    setShowFeedbackBubble(false);
                    setHasFreeCompletion(false);
                  }}
                >
                  自由运动
                </button>
              </div>
            </div>
            {mode === 'free' && (
              <div className="text-sm text-muted-foreground">
                综合强度：
                <span className="text-primary font-semibold ml-1">{Math.round(overallScore * 100)}%</span>
                {aiFeedback && (
                  <span className="ml-3 text-xs text-muted-foreground/80">
                    最新鼓励：{aiFeedback.encouragement}
                  </span>
                )}
              </div>
            )}
          </div>

          <div className="flex flex-col lg:flex-row gap-8 items-stretch">
            {/* 左侧：摄像头和指导 */}
            <div className="flex-1 flex flex-col">
              <div className="text-center mb-5 space-y-2">
                {mode === 'guided' ? (
                  <>
                    <div className="mx-auto w-16 h-16 rounded-full bg-mint/20 flex items-center justify-center text-3xl">
                      {currentAction?.emoji ?? '🍅'}
                    </div>
                    <h2 className="text-3xl font-bold text-primary">
                      休息时间到！让我们动起来 💪
                    </h2>
                    <p className="text-muted-foreground text-lg font-semibold">
                      {currentAction?.name ?? '舒展放松'}
                    </p>
                    <p className="text-muted-foreground">
                      {currentAction?.instructions ?? '跟随提示完成舒展动作'}
                    </p>
                    <p className="text-sm text-muted-foreground">
                      还需要完成 <span className="font-bold text-primary">{Math.max(effectiveTargetReps - currentReps, 0)}</span> 个动作
                    </p>
                  </>
                ) : (
                  <>
                    <div className="mx-auto w-16 h-16 rounded-full bg-tomato/20 flex items-center justify-center text-3xl">
                      🔥
                    </div>
                    <h2 className="text-3xl font-bold text-primary">自由运动模式开启</h2>
                    <p className="text-muted-foreground text-lg">
                      根据自己的节奏自由活动，AI 将实时评估你的运动强度
                    </p>
                    <p className="text-sm text-muted-foreground">
                      已活动时间 {elapsedSeconds.toFixed(0)} 秒 · 检测到动作 {repCount} 次
                    </p>
                  </>
                )}
              </div>

              <div className="relative rounded-3xl overflow-hidden shadow-lg border border-border/40 bg-gradient-to-br from-background via-card to-muted/40">
                <PoseCanvas
                  width={460}
                  height={mode === 'free' ? 360 : 340}
                  onPoseDetected={handlePoseDetected}
                />

                {/* 动作提示动画 */}
                <div className="absolute -top-12 left-1/2 -translate-x-1/2">
                  <div className="flex items-center justify-center w-14 h-14 bg-mint/30 rounded-full backdrop-blur-sm animate-bounce">
                    <span className="text-2xl">
                      {mode === 'guided' ? currentAction?.emoji ?? '✨' : '💪'}
                    </span>
                  </div>
                </div>

                <div className="absolute bottom-3 left-1/2 -translate-x-1/2 px-4 py-2 rounded-full bg-black/40 text-white text-sm backdrop-blur">
                  {mode === 'guided' ? 'AI 实时监测中，请保持身体在画面内' : '自由运动中，AI 正在评估你的运动强度'}
                </div>

                {mode === 'free' && showFeedbackBubble && feedbackQueue.length > 0 && (
                  <div className="absolute top-6 -right-4 w-52 bg-white/85 rounded-3xl backdrop-blur shadow-xl border border-border/40 p-4 space-y-2 transition-all duration-300">
                    <p className="text-xs text-muted-foreground">AI 实时反馈</p>
                    <p className="text-sm text-foreground leading-relaxed">
                      {feedbackQueue[feedbackQueue.length - 1]?.text}
                    </p>
                    <div className="text-xs text-muted-foreground/80 space-y-1">
                      {feedbackQueue[feedbackQueue.length - 1]?.suggestions?.map((s, idx) => (
                        <p key={idx}>• {s}</p>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div className="flex flex-col sm:flex-row justify-center gap-4 mt-6">
                <Button
                  onClick={onSkip}
                  variant="outline"
                  className="px-6 py-3 rounded-full backdrop-blur"
                >
                  {mode === 'guided' ? '跳过这次' : '提前结束'}
                </Button>
              </div>
            </div>

            {/* 右侧：番茄进度 */}
            <div className="w-full lg:w-72 flex flex-col items-center gap-6 bg-gradient-to-br from-mint/15 via-background to-tomato/10 rounded-3xl px-7 py-10 border border-border/40 shadow-lg">
              {mode === 'guided' ? (
                <>
                  <TomatoProgress progress={progress} size={240} />
                  <div className="text-center space-y-3">
                    <div className="text-4xl font-bold text-primary">
                      {currentReps} / {effectiveTargetReps}
                    </div>
                    <p className="text-muted-foreground leading-relaxed">
                      {currentReps === 0 && '开始第一个动作吧！'}
                      {currentReps > 0 && currentReps < effectiveTargetReps && '很好！保持节奏，继续完成剩余动作。'}
                      {currentReps >= effectiveTargetReps && '太棒了！动作完成，准备下一个番茄吧 ✨'}
                    </p>
                  </div>
                </>
              ) : (
                <>
                  <TomatoTree
                    totalTomatoes={5}
                    currentTomatoIndex={intensityMetrics.currentTomatoIndex}
                    currentProgress={intensityMetrics.currentTomatoProgress}
                    size={280}
                  />
                  <div className="w-full space-y-3 text-sm text-muted-foreground mt-2">
                    <div className="text-center">
                      <p className="text-base font-semibold text-primary">
                        综合强度 {Math.round(overallScore * 100)}%
                      </p>
                      <p className="text-xs mt-1">
                        {hasFreeCompletion ? '休息充足，可以继续专注啦 ✨' : `已活动 ${elapsedSeconds.toFixed(0)} 秒`}
                      </p>
                    </div>
                    <div className="space-y-2">
                      <div className="rounded-xl bg-white/50 p-3 shadow-sm">
                        <p className="text-xs text-muted-foreground mb-1 flex items-center justify-between">
                          <span>动作幅度</span>
                          <span className="text-primary font-semibold">{Math.round(amplitude * 100)}%</span>
                        </p>
                        <div className="h-2 rounded-full bg-muted/40 overflow-hidden relative">
                          <div
                            className="h-full bg-gradient-to-r from-tomato to-primary transition-all duration-300"
                            style={{ width: `${Math.round(amplitude * 100)}%` }}
                          />
                        </div>
                      </div>
                      <div className="rounded-xl bg-white/50 p-3 shadow-sm">
                        <p className="text-xs text-muted-foreground mb-1 flex items-center justify-between">
                          <span>动作次数</span>
                          <span className="text-primary font-semibold">{repCount}</span>
                        </p>
                        <div className="h-2 rounded-full bg-muted/40 overflow-hidden relative">
                          <div
                            className="h-full bg-gradient-to-r from-mint to-primary transition-all duration-300"
                            style={{ width: `${Math.min(100, Math.round(frequencyRatio * 100))}%` }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExerciseModal;